<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container" />
      <div class="login-main">
        <div class="login-title">欢迎使用——三宝金山中台</div>
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="login" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="off"
            @change="searchCompany()"
          />
        </el-form-item>

        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="passwordline" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            auto-complete="off"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
        <!-- <el-form-item prop="TENANT_ID">
          <span class="svg-container">
            <svg-icon icon-class="tenent" />
          </span>
          <el-select v-model="loginForm.TENANT_ID" clearable size="small" placeholder="请选择所属企业">
            <el-option
              v-for="item in companyTypes"
              :key="item.tenantId"
              :label="item.name"
              :value="item.tenantId"
            />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item prop="code">
          <span class="svg-container">
            <svg-icon icon-class="yanzheng" />
          </span>
          <el-input
            v-model="loginForm.code"
            size="small"
            :maxlength="code.len"
            auto-complete="off"
            placeholder="请输入验证码"
            style="width:160px;"
            name="code"
            @keyup.enter.native="handleLogin"
          />
          <div class="login-code">
            <span v-if="code.type == 'text'" class="login-code-img" @click="refreshCode">{{ code.value }}</span>
            <img v-else :src="code.src" alt="验证码" class="login-code-img" @click="refreshCode">
          </div>
        </el-form-item>-->
        <el-button
          :loading="loginLoading"
          type="primary"
          style="width: 100%; margin-top:38px; margin-bottom: 0px;"
          @click.native.prevent="handleLogin"
        >{{ loginText }}</el-button>
        <div class="edition">当前版本：v1.0.0</div>
      </div>
      <!-- 这是弹出框 -->
      <el-dialog
        title="选择租户"
        :visible.sync="dialogVisible"
        width="430px"
        top="50vh"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        custom-class="samples-dialog"
        :append-to-body="true"
        :before-close="handleClose"
      >
        <el-row style="padding: 25px 25px 10px;">
          <el-col :span="24">
            <el-form-item prop="TENANT_ID" label="所属租户：" label-width="100px">
              <!-- <span class="svg-container">
            <svg-icon icon-class="tenent" />
          </span> -->
              <el-select v-model="loginForm.TENANT_ID" clearable size="small" placeholder="请选择所属租户" style="width:100%">
                <el-option
                  v-for="item in companyTypes"
                  :key="item.tenantId"
                  :label="item.name"
                  :value="item.tenantId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- esc按钮和点击遮罩不会关闭弹窗，需要设置配置项 -->

        <el-row class="samples-dialog-footer">
          <el-row class="samples-float-right">
            <el-button
              size="small"
              type="primary"
              plain
              @click="handleClose"
            >取 消</el-button>
            <el-button size="small" type="primary" @click="handleLogin()">确 认</el-button>
          </el-row>
        </el-row>
      </el-dialog>

      <!-- 这是弹出框 -->
    </el-form>
  </div>
</template>

<script>
import { randomLenNum } from '@/utils/index'
import { mapGetters } from 'vuex'
// 获取 企业列表
import { getCompanyList } from '@/api/user.js'
// import { mapActions } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      // 弹出框
      dialogVisible: false,
      // 登录页加载效果
      loginText: '登 录',
      loginLoading: false,
      loginForm: {
        username: '',
        password: '',
        randomStr: '',
        platform: '1',
        TENANT_ID: null
      },
      code: {
        src: '/admin/code',
        value: '',
        len: 4,
        type: 'image'
      },
      loginRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度最少为6位', trigger: 'blur' }
        ],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
        // TENANT_ID: [
        //   { required: true, message: '请选择所属企业', trigger: 'change' }
        // ]
      },
      passwordType: 'password',
      redirect: undefined,
      companyTypes: []
    }
  },
  computed: {
    ...mapGetters(['tagWel'])
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.refreshCode()
  },
  mounted() {
    this.$refs['username'].focus()
  },
  methods: {
    // 弹出框关闭
    handleClose() {
      this.dialogVisible = false
      this.loginForm.TENANT_ID = null
    },
    searchCompany() {
      if (this.loginForm.username) {
        this.getCompany(this.loginForm.username)
      }
    },
    getCompany(name) {
      getCompanyList(name).then(res => {
        if (res.code === 1) {
          this.companyTypes = res.data
          // 如果获得的公司列表只有一个  那么直接显示出来
          if (this.companyTypes.length == 1) {
            this.loginForm.TENANT_ID = this.companyTypes[0].tenantId
          }
        } else {
          this.$notify({
            title: '失败',
            type: 'error',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    refreshCode() {
      this.loginForm.code = ''
      this.loginForm.randomStr = randomLenNum(this.code.len, true)
      this.code.type === 'text'
        ? (this.code.value = randomLenNum(this.code.len))
        : (this.code.src = 'admin/code/' + this.loginForm.randomStr)
      console.log(this.code.type === 'text')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      // console.log('登陆判断', this.companyTypes.length, this.loginForm.TENANT_ID)
      if (this.companyTypes.length > 1 && this.loginForm.TENANT_ID == null) {
        this.dialogVisible = true
      } else if (this.companyTypes.length == 0) {
        // console.log('等待查询租户接口返回数据，请重新点击登陆按钮')
        this.$message.error('该用户不存在！')
      } else {
        this.dialogVisible = false
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loginText = '登录中'
            this.loginLoading = true
            this.$store.dispatch('user/LoginByUsername', this.loginForm).then(
              res => {
                this.$store.commit('tags/ADD_TAG', this.tagWel)
                // this.loginText = '登录'
                this.$router.push({ path: this.tagWel.value })
              },
              error => {
                console.log(error)
                this.loginText = '登录'
                this.loginLoading = false
                this.refreshCode()
              }
            )
            // getCompanyList(this.loginForm.username).then(res => {
            //   if (res.code === 1) {
            //     this.companyTypes = res.data
            //     // 如果获得的公司列表只有一个  那么直接显示出来
            //     this.loginForm.TENANT_ID =
            //     (this.companyTypes[0] || {}).tenantId || ''
            //     this.$store.dispatch('user/LoginByUsername', this.loginForm).then(
            //       res => {
            //         this.$store.commit('tags/ADD_TAG', this.tagWel)
            //         // this.loginText = '登录'
            //         this.$router.push({ path: this.tagWel.value })
            //       },
            //       error => {
            //         console.log(error)
            //         this.loginText = '登录'
            //         this.loginLoading = false
            //         this.refreshCode()
            //       }
            //     )
            //   } else {
            //     this.loginText = '登录'
            //     this.loginLoading = false
            //     this.$notify({
            //       title: '失败',
            //       type: 'error',
            //       message: res.msg,
            //       duration: '3000'
            //     })
            //   }
            // })
          }
        })
      }
    }
  }
}
</script>
<style>
.edition {
  margin-top: 20px;
  color: #999999;
  font-size: 14px;
}
</style>

